// pages/servePost/servePost.js

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    "phone": "",
    "codes": [""],
    "name": "",
    "address": "",
    "addressGoods": "",
    "value": "",
    "packages": [1],
    "showPhone": false,
    "showAddress": false,
    "showAddressGoods": false,
    "acceptorPhone": "",
    "remark": "",
    "money": 0,
    "url": "/portal/orders/postOrder",
    "urlTrolley": "/portal/trolley/postTrolley",
  },

  // 展示帮助信息
  onClickPhone(e) {
    this.setData({
      showPhone: true
    })
  },
  onClickAddress(e) {
    if (e.currentTarget.dataset.address == 1) {
      this.setData({
        showAddress: true,
      });
    };
    if (e.currentTarget.dataset.address == 2) {
      this.setData({
        showAddressGoods: true,
      });
    };
  },

  // 关闭帮助信息
  onClose() {
    this.setData({ showPhone: false});
    this.setData({ showAddress: false });
    this.setData({ showAddressGoods: false });
  },

  // 改变包裹数量
  onChangePackages(e) {
    var lst = [1];
    var len = e.detail;
    if (e.detail > 5) len = 5; 
    for (var i = 2; i <= len; i++) {
      lst.push(i);
    };
    this.setData({
      packages: lst,
    });

    /* 更新codes的数量 */
    // 记录下来当前的codes
    var lc = this.data.codes;
    // 如果codes长度不足，插入空字符串
    for (let i = lc.length; i < len; i++) {
      lc.push("");
    };
    // 如果codes长度超长，pop掉多余的元素
    for (let i = lc.length; i > len; i--) {
      lc.pop();
    };
    // 更新codes
    this.setData({
      codes: lc,
    });
  },

  // 改变手机号
  onChangePhone(e) {
    this.setData({
      phone: e.detail,
    });
  },

  // 改变取件码
  onChangeCode(e) {
    // 按取件码的脚标更新
    this.setData({
      // 直接用this.setData({screenList[0].value ：新的值}) 的方法是会编译报错的
      // 所以需要用一个临时字符串变量，将数组名[索引值].属性名存储起来，再赋值
      [`codes[${e.currentTarget.dataset.index - 1}]`]: e.detail,
    });
  },

  // 改变姓名
  onChangeName(e) {
    this.setData({
      name: e.detail,
    });
  },

  // 改变地址
  onChangeAddress(e) {
    if (e.currentTarget.dataset.address == 1) {
      this.setData({
        address: e.detail,
      });
    };
    if (e.currentTarget.dataset.address == 2) {
      this.setData({
        addressGoods: e.detail,
      });
    };
  },

  // 改变收件人地址
  onChangeAcceptorName(e) {
    this.setData({
      acceptorName: e.detail,
    });
  },

  // 改变收件人手机号
  onChangeAcceptorPhone(e) {
    this.setData({
      acceptorPhone: e.detail,
    });
  },

  // 改变金额
  onChangeMoney(e) {
    this.setData({
      money: e.detail,
    });
  },

  onChangeRemark(e) {
    this.setData({
      remark: e.detail
    })
  },

  // 提交订单
  submit(e) {
    // 填写内容不能为空，如果为空返回，不执行后续操作
    if (this.data.phone == '' || codesStr == '' || this.data.name == '' || this.data.acceptorName == '' || this.data.address == '' || this.data.addressGoods == '' || this.data.acceptorPhone == '' || this.data.acceptorName  == '' || this.data.money == '') {
      Toast.fail('内容不能为空');
      return;
    }
    // 将取件码拼接为用逗号分割的字符串
    var codesStr = "";
    for (let index = 0; index < this.data.codes.length; index++) { 
      codesStr += this.data.codes[index];
      if (index < this.data.codes.length - 1) {
        codesStr += ",";
      }
    }

    Dialog.confirm({
      message: '您将支付'+this.data.money+'元',
    })
      .then(() => {
        // on confirm
        Toast.loading({
          duration: 0,
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
        });
        setTimeout(()=> {}, 1000)
        // 发送请求
        wx.request({
          url: this.data.url,
          method: "POST",
          data: {
              "orderPostUserPhone": this.data.phone,
              "goodsCode": codesStr,
              "orderPostUserName": this.data.name,
              "orderAcceptUserName": this.data.acceptorName,
              "addressAcceptor": this.data.address,
              "addressGoods": this.data.addressGoods,
              "orderAcceptUserPhone": this.data.acceptorPhone,
              "orderRemark": this.data.remark,
              "orderMoney": this.data.money,
              "userId": this.getUser().id,
          },
          headers: {
            'Content-Type': 'application/json'  // 从请求体发送json对象
          },
          success (res) {
            // 后端返回如果有误就返回，不执行后续操作
            if (res.data.code != 20001) {
              Toast.fail(res.data.msg);
              return;
            }
            Toast.success(res.data.msg);
            setTimeout(()=>
              {
                // 大括号里放需要延迟执行的代码
                wx.navigateBack({
                  delta: 1
                });
              }, 1000)
          },
          fail (res) {
            Toast.fail("网络异常");
          },
          complete() {
            setTimeout(()=>{
                // 大括号里放需要延迟执行的代码
                Toast.clear();
              }, 1000)
          }
        })
      })
      .catch(() => {
        // on cancel 
      });
  },

  // 加入购物车
  submitTrolley() {
    // 填写内容不能为空，如果为空返回，不执行后续操作
    if (this.data.phone == '' || codesStr == '' || this.data.name == '' || this.data.acceptorName == '' || this.data.address == '' || this.data.addressGoods == '' || this.data.acceptorPhone == '' || this.data.acceptorName  == '' || this.data.money == '') {
      Toast.fail('内容不能为空');
      return;
    }
    // 将取件码拼接为用逗号分割的字符串
    var codesStr = "";
    for (let index = 0; index < this.data.codes.length; index++) { 
      codesStr += this.data.codes[index];
      if (index < this.data.codes.length - 1) {
        codesStr += ",";
      }
    }
    
    Dialog.confirm({
      message: '确认加入购物车',
    })
      .then(() => {
        // on confirm
        Toast.loading({
          duration: 0,
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
        });
    
        wx.request({
          url: this.data.urlTrolley,
          method: "POST",
          data: {
            "orderPostUserPhone": this.data.phone,
            "goodsCode": codesStr,
            "orderPostUserName": this.data.name,
            "orderAcceptUserName": this.data.acceptorName,
            "addressAcceptor": this.data.address,
            "addressGoods": this.data.addressGoods,
            "orderAcceptUserPhone": this.data.acceptorPhone,
            "orderRemark": this.data.remark,
            "orderMoney": this.data.money,
            "userId": this.getUser().id,
          },
          success: (res) => {
            console.log(res);
            Toast(res.data.msg)
          },
          complete() {
            setTimeout(()=>{
                // 大括号里放需要延迟执行的代码
                Toast.clear();
              }, 1000)
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

 // 通过修改data里的值来修改默认值，默认为空串，
 // 函数从后端拿到数据后修改，该函数放到Onload里

  pickerConfirm(e) {
    this.setData({
      pickerHidden: true
    })
    this.setData({
      chosen: e.detail.value
    })
  },

  pickerCancel() {
    this.setData({
      pickerHidden: true
    })
  },

  pickerShow() {
    this.setData({
      pickerHidden: false
    })
  },

  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },

  formReset(e) {
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: ''
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      url: this.getWebsite() + this.data.url,
      urlTrolley: this.getWebsite() + this.data.urlTrolley,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 销毁挂载绑定
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})